package com.fgs.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.fgs.common.api.CommonConfig;
import com.fgs.common.appStatus.AppStatusConstant;
import com.fgs.common.appStatus.AppStatusManager;
import com.fgs.common.manager.ActivityManager;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.toolbar.IToolbar;
import com.fgs.common.toolbar.ToolbarOptions;
import com.fgs.common.toolbar.ToolbarStatus;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.jaeger.library.StatusBarUtil;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.system.KeyboardUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.ObservableTransformer;

/**
 * @author fgs
 * @date 2020/3/27
 **/

/**
 * 父类->基类->动态指定类型->泛型设计（通过泛型指定动态类型->由子类指定，父类只需要规定范围即可）
 */
public abstract class CommonActivity<V extends CommonView, P extends CommonPresenter<V>> extends RxAppCompatActivity implements CommonView, IToolbar, IToolbar.OnToolbarClickListener {

    public static final int REQUEST_CODE = 0;

    //引用V层和P层
    private P presenter;
    private V view;

    private int mLayoutId;
    private FragmentManager mFragmentManager;
    private CommonFragment mFragment;
    private Unbinder mUnbinder;

    protected String activityName = "";
    private IToolbar iToolbar;
    private ToolbarStatus mToolbarStatus;

    public P getPresenter() {
        return presenter;
    }

    //Android强制字体不随系统改变而改变
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        try {
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return res;
        }

    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
        super.onCreate(savedInstanceState);

        LogUtil.print("onCreate getAppStatus", getLocalClassName() + "--" + AppStatusManager.getInstance().getAppStatus() + "");

        switch (AppStatusManager.getInstance().getAppStatus()) {
            /**
             * 应用被强杀
             */
            case AppStatusConstant.STATUS_FORCE_KILLED:
                //跳到主页,主页lauchmode SINGLETASK
                protectApp();
                break;
            /**
             * 用户被踢或者TOKEN失效
             */
            case AppStatusConstant.STATUS_KICK_OUT:
                //弹出对话框,点击之后跳到主页,清除用户信息,运行退出登录逻辑
//                Intent intent=new Intent(this,MainActivity.class);
//                startActivity(intent);
                break;
            case AppStatusConstant.STATUS_NORMAL:
                onCreateNormal();
                break;
        }


    }

    protected void protectApp() {
        Class mainClass = CommonConfig.getInstance().commonOptions().getMainClass();
        if (mainClass != null) {
            Bundle bundle = new Bundle();
            bundle.putInt(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_RESTART_APP);
            openActivity(mainClass, bundle);
        }

    }

    private void onCreateNormal() {
        ActivityManager.getInstance().addActivity(this);

//        SwipeBackHelper.onCreate(this);
//        SwipeBackHelper.getCurrentPage(this).setSwipeBackEnable(false)
//        .setScrimColor(Color.parseColor("#F4F4F4"));
//
        //通过获取activity名字判断一些特殊的操作，比如主页面不需要滑动关闭
        try {
            activityName = getClass().getName().substring(getClass().getName().lastIndexOf(".") + 1);
//            SwipeBackHelper.getCurrentPage(this).setSwipeBackEnable(isUseSwipeBack(activityName));
        } catch (Exception e) {

        }

        //设置沉浸式状态栏
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0);

        mFragmentManager = getSupportFragmentManager();
        if (mLayoutId == 0) {
            mLayoutId = R.layout.activity_base;
        }
        setContentView(mLayoutId);

        int layoutId = getLayoutId();
        if (layoutId != 0) {
            FrameLayout container = findViewById(R.id.activity_container);
            LayoutInflater inflater = LayoutInflater.from(this);
            if (inflater != null) {
                View view = inflater.inflate(layoutId, null);
                if (view != null) {
                    container.addView(view);
                }
            }
        }

        mUnbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        if (presenter == null) {
            presenter = createPresenter();
        }
        if (view == null) {
            view = createView();
        }
        if (presenter != null && view != null) {
            presenter.attachView(view);
        }

        mFragment = (CommonFragment) mFragmentManager.findFragmentById(R.id.activity_container);
        if (null == mFragment) {
            mFragment = createFragment();
            if (null != mFragment) {
                FragmentTransaction transaction = mFragmentManager.beginTransaction();
                transaction.add(R.id.activity_container, mFragment);
                transaction.commit();
            }
        }

        Bundle extras = getIntent().getExtras();
        if (extras != null && mFragment != null) {
            if (mFragment.getArguments() == null) {
                mFragment.setArguments(extras);
            } else {
                mFragment.getArguments().putAll(extras);
            }
        }


        initToolBar();
        init();
    }

    private boolean isUseSwipeBack(String activityName) {
        switch (activityName) {
            case "LoginActivity":
            case "MainActivity":
            case "SplashActivity":
            case "DriverAuthenticationActivity":
            case "VehicleAuthenticationActivity":
            case "OrderCancelActivity":
            case "OrderLoadingActivity":
            case "OrderDeliveryActivity":
                return false;
        }
        return true;
    }

    private void initToolBar() {
        iToolbar = this;
        Toolbar toolbar = findViewById(R.id.layout_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        ToolbarOptions options = new ToolbarOptions();
        options.setToolbar(toolbar)
                .setTitleTextView(findViewById(R.id.layout_toolbar_title))
                .setSubtitleTextView(findViewById(R.id.layout_toolbar_subtitle))
                .setBackIconImageView(findViewById(R.id.layout_toolbar_backImageView))
                .setBackRelativeLayout(findViewById(R.id.layout_toolbar_backRelativeLayout))
                .setTitle(iToolbar.getToolbarTitle())
                .setSubtitle(iToolbar.getToolbarSubtitle())
                .setIsToolbarShow(iToolbar.isShowToolbar())
                .setIsBackIconShow(iToolbar.isShowBackIcon())
                .setBackIcon(iToolbar.getBackIcon());
        ToolbarStatus toolbarStatus = new ToolbarStatus();
        toolbarStatus.setOnToolbarClickListener(this);
        toolbarStatus.setToolbarOptions(options);
        toolbarStatus.initToolbar();
        iToolbar.setToolbarStatus(toolbarStatus);

    }

    @Override
    public void onSubtitleClick() {

    }

    @Override
    public void onBackIconClick() {
        onBackPressed();
    }

    //由子类指定具体类型
    public abstract int getLayoutId();

    public abstract P createPresenter();

    public abstract V createView();

    public abstract void init();

    /**
     * activity中需要fragment时，调用此方法添加所需的页面布局
     */
    public abstract CommonFragment createFragment();


    @Override
    public String getToolbarTitle() {
        return getTitle().toString();
    }

    @Override
    public String getToolbarSubtitle() {
        return null;
    }

    @Override
    public boolean isShowToolbar() {
        return true;
    }

    @Override
    public boolean isShowBackIcon() {
        return true;
    }

    @Override
    public int getBackIcon() {
        return R.mipmap.icon_back;
    }

    @Override
    public void setToolbarStatus(ToolbarStatus toolbarStatus) {
        mToolbarStatus = toolbarStatus;
    }

    @Override
    public ToolbarStatus getToolbarStatus() {
        return mToolbarStatus;
    }

    protected void setTitle(String title) {
        getToolbarStatus().setTitle(title);
    }

    protected void setSubTitle(String subtitle) {
        getToolbarStatus().setSubtitle(subtitle);
    }

    protected void setSubTitleColor(int color) {
        getToolbarStatus().setSubtitleColor(getResources().getColor(color));
    }

    protected void toolbarHide() {
        getToolbarStatus().isShowToolbar(false);
    }

    protected void toolbarShow() {
        getToolbarStatus().isShowToolbar(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
        EventBus.getDefault().unregister(this);

        ActivityManager.getInstance().finishActivity(this);

        if (mUnbinder != null)
            mUnbinder.unbind();
//        SwipeBackHelper.onDestroy(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CommonEvent event) {

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.left_in, R.anim.left_out);
    }

    public void openActivity(Class<?> pClass) {
        Intent intent = new Intent(this, pClass);
        startActivity(intent);
    }

    public void openActivityForResult(Class<?> pClass) {
        Intent intent = new Intent(this, pClass);
        startActivityForResult(intent, REQUEST_CODE);
    }

    public void openActivityForResult(int requestCode, Class<?> pClass) {
        Intent intent = new Intent(this, pClass);
        startActivityForResult(intent, requestCode);
    }

    public void openActivityForResult(int requestCode, Class<?> pClass, Bundle bundle) {
        Intent intent = new Intent(this, pClass);
        intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
    }

    public void openActivityForResult(Class<?> pClass, Bundle bundle) {
        Intent intent = new Intent(this, pClass);
        intent.putExtras(bundle);
        startActivityForResult(intent, REQUEST_CODE);
    }

    public void openActivity(Class<?> pClass, Bundle bundle) {
        Intent intent = new Intent(this, pClass);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    protected void hideKeyboard() {

        try {
            KeyboardUtils.hideSoftInput(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showKeyboard(View view) {

        try {
            KeyboardUtils.showSoftInput(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showKeyboard() {

        try {
            KeyboardUtils.showSoftInput(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 简单的提示性对话框
     */
    protected void showSimpleTipDialog() {
        String content = "";
        if (!TextUtils.isEmpty(getTipMessage())) {
            content = getTipMessage() + "，";
        }
        new MaterialDialog.Builder(this)
                .content(content + "确定要退出吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                })
                .show();
    }

    protected String getTipMessage() {
        return "";
    }

    @Override
    public void setMsg(String msg) {
        showToast(msg);
    }

    @Override
    public <T> ObservableTransformer<T, T> bindLifecycle() {
        return this.bindToLifecycle();
    }

    public void showToast(String message) {
        ToastUtil.showShortToast(message);
    }

    public void showToast(int msgId) {
        ToastUtil.showShortToast(msgId);
    }

    public void showTipDialog(String tip) {
        new MaterialDialog.Builder(getContext())
                .content(tip)
                .positiveText("知道了")
                .show();
    }

    public void showTipDialog(String tip, String operateTip, MaterialDialog.SingleButtonCallback singleButtonCallback) {
        new MaterialDialog.Builder(getContext())
                .content(tip)
                .positiveText(operateTip)
                .onPositive(singleButtonCallback)
                .show();
    }


//    @Override
//    protected void onPostCreate(Bundle savedInstanceState) {
//        super.onPostCreate(savedInstanceState);
//        SwipeBackHelper.onPostCreate(this);
//    }


    @Override
    public void onBackPressed() {
        if (isShowFinishTipDialog()) {
            showSimpleTipDialog();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 退出activity时，是否显示退出提示框
     *
     * @return
     */
    protected boolean isShowFinishTipDialog() {
        return false;
    }


    @Override
    public Context getContext() {
        return this;
    }

}
